package com.shuai.chatroom.config;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class UserOnLineStateManager {
    private final ConcurrentHashMap<Integer, WebSocketSession> userSessions = new ConcurrentHashMap<>();

    public void upLine(Integer uId, WebSocketSession session) {
        if (userSessions.get(uId) != null) {
            return; //用户已经上线了
        }
        userSessions.put(uId, session);
    }

    public void offLine(Integer uId, WebSocketSession session) {
        WebSocketSession existsSession = userSessions.get(uId);
        if (session == existsSession) {
            userSessions.remove(uId);   //确定下线用户和当前已经在线的用户是同一个。防止多开情况下同一用户断开连接时也断开之前已经建立连接的客户端
        }
    }

    public WebSocketSession getUserSession(Integer uId) {
        return userSessions.get(uId);
    }

}
